package com.hy.study.reduce;

import com.hy.study.bean.JoinTableBean;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author huyong
 * @date 2024 年 02 月 06 日 14:23: 53
 */
public class JoinTableReducer extends Reducer<Text, JoinTableBean, JoinTableBean, NullWritable> {
    @Override
    protected void reduce(Text key, Iterable<JoinTableBean> values, Reducer<Text, JoinTableBean, JoinTableBean, NullWritable>.Context context) throws IOException, InterruptedException {
        List<JoinTableBean> orderList = new ArrayList<>();// 存放订单信息
        JoinTableBean productInfo = new JoinTableBean();// 存放产品信息
        try {
            for (JoinTableBean value : values) {
                if ("order".equalsIgnoreCase(value.getFlag())) {
                    // 这里不能直接添加需要进行深拷贝
                    JoinTableBean tempBean = new JoinTableBean();
                    BeanUtils.copyProperties(tempBean, value);
                    orderList.add(tempBean);
                } else {
                    BeanUtils.copyProperties(productInfo, value);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        for (JoinTableBean order : orderList) {
            order.setPname(productInfo.getPname());
            context.write(order, NullWritable.get());
        }

    }
}
